package com.dbq.fast.business.setting;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.dbq.fast.business.me.bean.VersionBean;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.SpUtil;
import com.yiba.logutils.utils.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.leolin.shortcutbadger.ShortcutBadger;

public class UpdateLogic {

    private final Activity activity;
    private OnUpdateListener listener;
    private static DownloadService.DownloadServiceBinder mBinder;
    private static boolean isDownloading = false;
    private VersionBean versionBean;
    private static boolean isDownloadComplete = false;
    private static boolean isBind = false;

    private final int START_DOWNLOAD = 1000;
    private final int DOWNLOADING = 1001;
    private final int DOWNLOAD_COMPLETE = 1002;
    private static int DOWNLOAD_STATUS = 0000;

    public UpdateLogic(Activity activity) {
        this.activity = activity;
        Intent intentService = new Intent(activity, DownloadService.class);
        activity.startService(intentService);
        if (!isBind) {
            isBind = activity.bindService(intentService, conn, Context.BIND_AUTO_CREATE);
        }
    }


    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = (DownloadService.DownloadServiceBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBinder = null;
        }
    };

    private DownloadService.OnDownloadStatusListener downloadStatusListener = new DownloadService.OnDownloadStatusListener() {
        @Override
        public void start() {
            DOWNLOAD_STATUS = START_DOWNLOAD;
            isDownloading = true;
            isDownloadComplete = false;
        }


        @Override
        public void downloadError() {
            isDownloading = false;
            errorNotify();
        }

        @Override
        public void writeLocaling() {
            isDownloading = true;

        }

        @Override
        public void writePercent(long fileSizeDownloaded, long total) {
            percentNotify(fileSizeDownloaded, total);
            DOWNLOAD_STATUS = DOWNLOADING;
        }


        @Override
        public void writeLocalError() {
            isDownloading = false;
            errorNotify();

        }

        @Override
        public void complete() {
            isDownloading = false;
            isDownloadComplete = true;
            DOWNLOAD_STATUS = DOWNLOAD_COMPLETE;
            completeNotify();
        }
    };

    public boolean isDownComplete() {
        return DOWNLOAD_STATUS == DOWNLOAD_COMPLETE;
    }

    public void autoDownloadApk() {
        if (isDownloading) return;
        SettingApi.checkUpdate(new RemoteApiCallBack<VersionBean>() {
            @Override
            public void onSuccess(VersionBean versionBean) {
                Log.i("versionBean", "versionBean = " + versionBean.toString());
                if (isWifi(activity) && !apkExists(versionBean.apkName)) {
                    mBinder.getService().downloadApk(versionBean.apkName, versionBean.updateApkUrl, downloadStatusListener);
                }
            }

            @Override
            public void onFail(int status, String message) {
            }
        });


    }


    public void handleDownloadApk() {
            mBinder.getService().downloadApk(versionBean.apkName, versionBean.updateApkUrl, downloadStatusListener);
    }

    private boolean hasOneDay() {
        long time = SpUtil.getLong("oneDay");
        if (new Date().getTime() - time > 1 * 10 * 1000) {//1 * 24 * 60 * 60 * 1000 // * 60 * 60
            SpUtil.setLong("oneDay", new Date().getTime());
            return true;
        }
        return true;
    }

    public void autoTipUpdate() {
        if (hasOneDay()) { //是否有一天，如果有一天则提示，如果没有一天，则到有一天才提示。
            SettingApi.checkUpdate(new RemoteApiCallBack<VersionBean>() {

                @Override
                public void onSuccess(VersionBean versionBean) {
                    UpdateLogic.this.versionBean = versionBean;
                    if (versionBean.isHaveNewVersion()) {
                        int badgeCount = 1;
                        ShortcutBadger.applyCount(activity, badgeCount); //for 1.1.4+
                    } else {
                        ShortcutBadger.removeCount(activity); //for 1.1.4+
                        currentIsLastVersion();
                    }
                    if (apkExists(versionBean.apkName)) {
                        updateNotifyUpdate();
                    }
                }

                @Override
                public void onFail(int status, String message) {
                }
            });
        }

    }

    private void errorNotify() {
        if (!updateStatus.isEmpty()) {
            listener = this.updateStatus.get(updateStatus.size() - 1);
            listener.downError();
        }
    }

    private void updateNotifyUpdate() {
        if (!updateStatus.isEmpty()) {
            listener = this.updateStatus.get(updateStatus.size() - 1);
            listener.update(versionBean);
        }
    }

    private void currentIsLastVersion() {
        if (!updateStatus.isEmpty()) {
            listener = this.updateStatus.get(updateStatus.size() - 1);
            listener.isLastVersion();
        }
    }

    private void completeNotify() {
        if (!updateStatus.isEmpty()) {
            listener = this.updateStatus.get(updateStatus.size() - 1);
            listener.downComplete(versionBean);
        }
    }

    private void percentNotify(long part, long total) {
        if (!updateStatus.isEmpty()) {
            for (OnUpdateListener l : this.updateStatus) {
                l.onPercent(part, total);
            }
//            listener = this.updateStatus.get(updateStatus.size() - 1);
        }
    }

    public void checkVersion() {
        //检查是否有先的版本
        //新的版本是否已经下载,本地sd的读写权限是否拥有
        //如果没有检查到新的版本，不显示 更新版本的条目
        //在wifi条件下下载
        SettingApi.checkUpdate(new RemoteApiCallBack<VersionBean>() {

            @Override
            public void onSuccess(VersionBean versionBean) {
                UpdateLogic.this.versionBean = versionBean;
                updateNotifyUpdate();

            }

            @Override
            public void onFail(int status, String message) {
            }
        });

    }


    private boolean apkExists(String apkName) {
//        File apkFile = new File(FileUtil.getTempDirPath(activity) + "/" + apkName + ".apk");
        String existsName = SpUtil.getString("apkName");
//        apkFile.
        return existsName.equals(apkName);//apkFile.exists();
    }

    private static List<OnUpdateListener> updateStatus = new ArrayList<>();

    public void setOnUpdateListener(OnUpdateListener listener) {
        this.updateStatus.add(listener);
    }

    public interface OnUpdateListener {
        void update(VersionBean versionBean);

        void downComplete(VersionBean versionBean);

        void onPercent(long part, long total);

        void downError();

        void isLastVersion();
    }

    private static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null
                && info.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    public boolean installApk() {
        if (!apkExists(versionBean.apkName)) {
            return false;
        }
        File apkFile = new File(FileUtil.getTempDirPath(activity) + "/" + versionBean.apkName);
        installApk(apkFile);
        return true;
    }

    private void installApk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            Uri contentUri = FileProvider.getUriForFile(activity.getApplicationContext(), "com.unicorn.china.provider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        activity.startActivity(intent);
    }


    public void onDestory() {
        if (activity != null && conn != null && isBind) {
            try {
                activity.unbindService(conn);
                isBind = false;
            } catch (Exception e) {
            }

        }
    }
}
